package com.agent.auth.controller;

import com.agent.auth.entity.UserSession;
import com.agent.auth.service.AuthService;
import com.agent.auth.service.GoogleAuthService;
import com.agent.common.entity.TokenPair;
import com.agent.common.result.ApiResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

/**
 * 认证控制器
 * @author Jeff_Wan
 * @description 处理用户认证相关请求
 */
@RestController
@RequestMapping("/auth")
@RequiredArgsConstructor
public class AuthController {

    private final AuthService authService;
    private final GoogleAuthService googleAuthService;

    /**
     * Google登录回调
     * @param code 授权码
     * @return JWT令牌对
     */
    @GetMapping("/login/google/callback")
    public ApiResponse<TokenPair> googleCallback(@RequestParam String code) {
        TokenPair token = googleAuthService.handleGoogleCallback(code);
        return ApiResponse.success(token);
    }

    /**
     * 邮箱登录
     * @param email 邮箱
     * @param password 密码
     * @return JWT令牌
     */
    @PostMapping("/email/login")
    public ApiResponse<TokenPair> loginWithEmail(
            @RequestParam String email,
            @RequestParam String password) {
        TokenPair token = authService.loginWithEmail(email, password);
        return ApiResponse.success(token);
    }

    /**
     * 验证令牌有效性
     * @param token JWT令牌
     * @return 验证结果
     */
//    @GetMapping("/validate")
    public ApiResponse<Boolean> validateToken(@RequestParam String token) {
        try {
            authService.validateAndExtractUserContext(token);
            return ApiResponse.success(true);
        } catch (Exception e) {
            return ApiResponse.success(false);
        }
    }

    /**
     * 刷新访问令牌
     * @param refreshToken 刷新令牌
     * @return 新的令牌对
     */
    @PostMapping("/refresh")
    public ApiResponse<TokenPair> refreshToken(@RequestParam String refreshToken) {
        TokenPair tokenPair = authService.renewAccessToken(refreshToken);
        return ApiResponse.success(tokenPair);
    }

    /**
     * 获取当前会话信息
     * @param accessToken 访问令牌
     * @return 会话信息
     */
    @GetMapping("/session")
    public ApiResponse<UserSession> getSession(@RequestParam String accessToken) {
        UserSession session = authService.getSessionByToken(accessToken);
        return ApiResponse.success(session);
    }

    /**
     * 退出登录
     * @param token JWT令牌
     * @return 操作结果
     */
    @PostMapping("/logout")
    public ApiResponse<Void> logout(@RequestParam String token) {
        authService.logout(token);
        return ApiResponse.success();
    }
}